#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
偏好设置对话框模块
提供应用程序设置界面
"""

import logging
from typing import Dict, Any

from PySide6.QtCore import Qt, QTimer
from PySide6.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QTabWidget,
                              QWidget, QFormLayout, QComboBox, QSpinBox,
                              QCheckBox, QDialogButtonBox, QLabel, QGroupBox,
                              QPushButton, QMessageBox, QTextEdit, QFontComboBox,
                              QSlider, QFrame)
from PySide6.QtGui import QFont

from config.settings import settings
from config.constants import DEFAULT_ENCODINGS, CSV_DELIMITERS, THEMES
from core.i18n import i18n, tr
from ui.style_manager import get_style_manager


# 初始化日志记录器
logger = logging.getLogger("preferences")


class PreferencesDialog(QDialog):
    """偏好设置对话框"""
    
    def __init__(self, parent=None):
        """初始化偏好设置对话框
        
        Args:
            parent: 父窗口
        """
        super().__init__(parent)
        self.setWindowTitle(tr("preferences_title", "偏好设置"))
        self.resize(600, 500)
        self._init_ui()
        self._load_settings()
        
    def _init_ui(self):
        """初始化UI"""
        # 主布局
        layout = QVBoxLayout(self)
        
        # 选项卡
        tab_widget = QTabWidget()
        
        # 常规设置选项卡
        general_tab = QWidget()
        general_layout = QFormLayout(general_tab)
        
        # # 主题设置
        # self.theme_combo = QComboBox()
        # self.theme_combo.addItem(tr("theme_auto", "跟随系统"), "auto")
        # self.theme_combo.addItem(tr("theme_light", "浅色"), "modern_light")
        # self.theme_combo.addItem(tr("theme_dark", "深色"), "modern_dark")
        # general_layout.addRow(tr("general_theme", "主题:"), self.theme_combo)
        #
        # 语言设置
        self.language_combo = QComboBox()
        supported_languages = i18n.get_supported_languages()
        for lang_code, lang_name in supported_languages.items():
            self.language_combo.addItem(lang_name, lang_code)
        general_layout.addRow(tr("general_language", "语言:"), self.language_combo)
        
        # 默认编码
        self.encoding_combo = QComboBox()
        for encoding in DEFAULT_ENCODINGS:
            self.encoding_combo.addItem(encoding)
        general_layout.addRow(tr("general_encoding", "默认编码:"), self.encoding_combo)
        
        # CSV默认分隔符
        self.delimiter_combo = QComboBox()
        for delimiter in CSV_DELIMITERS:
            if delimiter == ",":
                display_text = tr("delimiter_comma", "逗号 (,)")
            elif delimiter == ";":
                display_text = tr("delimiter_semicolon", "分号 (;)")
            elif delimiter == "|":
                display_text = tr("delimiter_pipe", "竖线 (|)")
            elif delimiter == "\t":
                display_text = tr("delimiter_tab", "制表符 (\\t)")
            else:
                display_text = delimiter
                
            self.delimiter_combo.addItem(display_text, delimiter)
        general_layout.addRow(tr("general_csv_delimiter", "CSV默认分隔符:"), self.delimiter_combo)

        # 编辑器设置选项卡
        editor_tab = QWidget()
        editor_layout = QVBoxLayout(editor_tab)
        
        # 字体设置组
        font_group = QGroupBox(tr("editor_font_settings", "字体设置"))
        font_layout = QFormLayout()
        
        # 字体选择
        self.font_combo = QFontComboBox()
        self.font_combo.setFontFilters(QFontComboBox.MonospacedFonts)
        self.font_combo.currentFontChanged.connect(self._update_preview)
        font_layout.addRow(tr("editor_font_family", "字体:"), self.font_combo)
        
        # 字体大小
        font_size_layout = QHBoxLayout()
        self.font_size_spin = QSpinBox()
        self.font_size_spin.setRange(8, 72)
        self.font_size_spin.setValue(12)
        self.font_size_spin.setSuffix(" pt")
        self.font_size_spin.valueChanged.connect(self._update_preview)
        
        self.font_size_slider = QSlider(Qt.Horizontal)
        self.font_size_slider.setRange(8, 72)
        self.font_size_slider.setValue(12)
        self.font_size_slider.valueChanged.connect(self.font_size_spin.setValue)
        self.font_size_spin.valueChanged.connect(self.font_size_slider.setValue)
        
        font_size_layout.addWidget(self.font_size_spin)
        font_size_layout.addWidget(self.font_size_slider)
        font_layout.addRow(tr("editor_font_size", "字体大小:"), font_size_layout)
        
        font_group.setLayout(font_layout)
        editor_layout.addWidget(font_group)
        
        # 编辑器行为设置组
        behavior_group = QGroupBox(tr("editor_behavior_settings", "编辑器行为"))
        behavior_layout = QFormLayout()
        
        # Ctrl+滚轮缩放设置
        self.wheel_zoom_check = QCheckBox(tr("button_enable", "启用"))
        self.wheel_zoom_check.setToolTip(tr("editor_wheel_zoom_tooltip", "启用后可以使用 Ctrl + 滚轮调节编辑器字体大小"))
        behavior_layout.addRow(tr("editor_wheel_zoom", "Ctrl+滚轮缩放:"), self.wheel_zoom_check)
        
        behavior_group.setLayout(behavior_layout)
        editor_layout.addWidget(behavior_group)
        
        # 预览区域
        preview_group = QGroupBox(tr("editor_preview", "预览"))
        preview_layout = QVBoxLayout()
        
        self.preview_text = QTextEdit()
        self.preview_text.setMaximumHeight(150)
        self.preview_text.setReadOnly(True)  # 设置为只读
        self.preview_text.setPlainText(
            "-- SQL查询示例预览\n"
            "SELECT id, name, email\n"
            "FROM users\n"
            "WHERE created_at > '2023-01-01'\n"
            "  AND status = 'active'\n"
            "ORDER BY id DESC\n"
            "LIMIT 100;"
        )
        preview_layout.addWidget(self.preview_text)
        
        # 添加预览说明标签
        preview_note = QLabel(tr("editor_preview_note", "预览区域显示了当前字体设置的效果"))
        preview_note.setObjectName("preview_note")
        preview_layout.addWidget(preview_note)
        
        preview_group.setLayout(preview_layout)
        editor_layout.addWidget(preview_group)
        
        # 添加弹性空间
        editor_layout.addStretch()
        
        # 查询设置选项卡
        query_tab = QWidget()
        query_layout = QFormLayout(query_tab)
        
        # 查询超时设置
        self.timeout_spin = QSpinBox()
        self.timeout_spin.setRange(1, 3600)
        self.timeout_spin.setSingleStep(5)
        self.timeout_spin.setSuffix(f" {tr('seconds', '秒')}")
        query_layout.addRow(tr("query_timeout", "查询超时时间:"), self.timeout_spin)
        
        # 自动保存查询
        self.auto_save_check = QCheckBox(tr("button_enable", "启用"))
        self.auto_save_check.setChecked(True)
        query_layout.addRow(tr("query_auto_save", "自动保存查询:"), self.auto_save_check)
        
        # 历史记录设置
        history_group = QGroupBox(tr("query_history", "历史记录"))
        history_layout = QFormLayout()
        
        # 清空历史按钮
        clear_history_button = QPushButton(tr("query_clear_history", "清空历史记录"))
        clear_history_button.clicked.connect(self._clear_history)
        history_layout.addRow("", clear_history_button)
        
        history_group.setLayout(history_layout)
        query_layout.addRow(history_group)
        
        # 添加选项卡
        tab_widget.addTab(general_tab, tr("preferences_general", "常规"))
        tab_widget.addTab(editor_tab, tr("preferences_editor", "编辑器"))
        tab_widget.addTab(query_tab, tr("preferences_query", "查询"))
        
        layout.addWidget(tab_widget)
        
        # 按钮
        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel | QDialogButtonBox.Apply
        )
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        button_box.button(QDialogButtonBox.Apply).clicked.connect(self._apply_settings)
        
        layout.addWidget(button_box)
    
    def _update_preview(self):
        """更新预览"""
        try:
            # 获取选择的字体和大小
            font = self.font_combo.currentFont()
            size = self.font_size_spin.value()
            
            logger.info(f"更新预览 - 选择的字体: {font.family()}, 大小: {size}")
            
            # 应用到预览区域
            preview_font = QFont(font)
            preview_font.setPointSize(size)
            preview_font.setFixedPitch(True)
            
            # 检查字体设置前的状态
            old_font = self.preview_text.font()
            logger.info(f"预览区域原字体: {old_font.family()}, 大小: {old_font.pointSize()}")
            
            self.preview_text.setFont(preview_font)
            
            # 强制刷新显示
            self.preview_text.update()
            
            # 验证字体是否设置成功
            actual_font = self.preview_text.font()
            logger.info(f"预览区域新字体: {actual_font.family()}, 大小: {actual_font.pointSize()}")
            
            # 如果字体设置失败，尝试使用样式表方式
            if actual_font.family() != font.family() or actual_font.pointSize() != size:
                logger.warning(f"字体设置失败，尝试使用样式表方式")
                self.preview_text.setStyleSheet(f"""
                    QTextEdit {{
                        font-family: "{font.family()}", monospace;
                        font-size: {size}pt;
                    }}
                """)
                
        except Exception as e:
            logger.error(f"更新预览失败: {e}")
            import traceback
            traceback.print_exc()
            
    def _load_settings(self):
        """加载当前设置"""
        # 主题 - 使用样式管理器的API
        style_manager = get_style_manager()
        current_theme = style_manager.get_theme_setting()
        
        # for i in range(self.theme_combo.count()):
        #     if self.theme_combo.itemData(i) == current_theme:
        #         self.theme_combo.setCurrentIndex(i)
        #         break
        
        # 语言
        language = settings.get("language", "auto")
        for i in range(self.language_combo.count()):
            if self.language_combo.itemData(i) == language:
                self.language_combo.setCurrentIndex(i)
                break
        
        # 编码
        encoding = settings.get("default_encoding")
        index = self.encoding_combo.findText(encoding)
        if index >= 0:
            self.encoding_combo.setCurrentIndex(index)
            
        # 分隔符
        delimiter = settings.get("csv_delimiter")
        for i in range(self.delimiter_combo.count()):
            if self.delimiter_combo.itemData(i) == delimiter:
                self.delimiter_combo.setCurrentIndex(i)
                break
        
        # 编辑器字体设置
        editor_font_family = settings.get("editor_font_family", "Consolas")
        editor_font_size = settings.get("editor_font_size", 12)
        
        logger.info(f"加载字体设置: {editor_font_family}, 大小: {editor_font_size}")
        
        # 设置字体 - 改进字体查找逻辑
        # 首先尝试按名称查找字体
        found_font = False
        for i in range(self.font_combo.count()):
            font = self.font_combo.itemData(i, Qt.FontRole)
            if font and font.family() == editor_font_family:
                self.font_combo.setCurrentIndex(i)
                found_font = True
                logger.info(f"找到字体: {font.family()}")
                break
        
        # 如果没有找到精确匹配，使用setCurrentFont方法
        if not found_font:
            target_font = QFont(editor_font_family)
            target_font.setFixedPitch(True)
            self.font_combo.setCurrentFont(target_font)
            logger.info(f"使用setCurrentFont设置字体: {target_font.family()}")
        
        # 设置字体大小
        self.font_size_spin.setValue(editor_font_size)
        self.font_size_slider.setValue(editor_font_size)
        
        # 编辑器行为设置
        enable_wheel_zoom = settings.get("enable_editor_wheel_zoom", True)
        self.wheel_zoom_check.setChecked(enable_wheel_zoom)
        
        # 延迟更新预览，确保所有控件都已经设置完毕
        QTimer.singleShot(100, self._update_preview)
                
        # 查询超时
        self.timeout_spin.setValue(settings.get("query_timeout", 30))
        
        # 自动保存查询
        self.auto_save_check.setChecked(settings.get("auto_save_queries", True))
        
    def _apply_settings(self):
        """应用设置"""
        # 主题 - 使用样式管理器的API
        # theme_index = self.theme_combo.currentIndex()
        # theme = self.theme_combo.itemData(theme_index)
        #
        # style_manager = get_style_manager()
        # old_theme = style_manager.get_theme_setting()
        #
        # if theme != old_theme:
        #     if style_manager.set_theme(theme):
        #         logger.info(f"主题已切换为: {theme}")
        #     else:
        #         logger.error(f"切换主题失败: {theme}")
        
        # 语言
        language_index = self.language_combo.currentIndex()
        language = self.language_combo.itemData(language_index)
        old_language = settings.get("language", "auto")
        settings.set("language", language)
        
        # 如果语言发生变化，更新国际化管理器
        if old_language != language:
            i18n.set_language(language)
        
        # 编码
        encoding = self.encoding_combo.currentText()
        settings.set("default_encoding", encoding)
        
        # 分隔符
        delimiter_index = self.delimiter_combo.currentIndex()
        delimiter = self.delimiter_combo.itemData(delimiter_index)
        settings.set("csv_delimiter", delimiter)
        
        # 编辑器字体设置
        editor_font_family = self.font_combo.currentFont().family()
        editor_font_size = self.font_size_spin.value()
        settings.set("editor_font_family", editor_font_family)
        settings.set("editor_font_size", editor_font_size)
        
        # 编辑器行为设置
        enable_wheel_zoom = self.wheel_zoom_check.isChecked()
        settings.set("enable_editor_wheel_zoom", enable_wheel_zoom)
        
        # 查询超时
        timeout = self.timeout_spin.value()
        settings.set("query_timeout", timeout)
        
        # 自动保存查询
        auto_save = self.auto_save_check.isChecked()
        settings.set("auto_save_queries", auto_save)
        
        # 保存设置
        settings.save_settings()
        
        # 立即应用字体设置到所有打开的编辑器
        self._apply_settings_to_editors()
        
        # 提示
        logger.info("设置已保存")
        
        # 如果语言发生变化，提示重启
        if old_language != language:
            from PySide6.QtWidgets import QMessageBox
            QMessageBox.information(
                self, 
                tr("settings_saved", "设置已保存"),
                tr("language_change_restart", "语言更改将在重启应用后生效")
            )
    
    def _apply_settings_to_editors(self):
        """应用设置到所有编辑器"""
        try:
            # 查找主窗口
            from PySide6.QtWidgets import QApplication
            app = QApplication.instance()
            if app:
                for widget in app.allWidgets():
                    # 查找主窗口
                    if hasattr(widget, 'sql_editor') and hasattr(widget.sql_editor, 'apply_font_settings'):
                        logger.info("找到主窗口，应用字体设置到SQL编辑器")
                        widget.sql_editor.apply_font_settings()
                        break
        except Exception as e:
            logger.error(f"应用设置到编辑器失败: {e}")
        
    def _clear_history(self):
        """清空历史记录"""
        reply = QMessageBox.question(
            self, 
            tr("confirm_clear_history", "确认清空"), 
            tr("confirm_clear_history_message", "确定要清空文件和查询历史记录吗？\n此操作不可撤销。"), 
            QMessageBox.Yes | QMessageBox.No
        )
        
        if reply == QMessageBox.Yes:
            # 清空最近文件
            settings.set("recent_files", [])
            settings.save_settings()
            
            # 应该同时清空数据库中的查询历史
            from core.query_manager import get_query_manager
            query_manager = get_query_manager()
            query_manager.clear_query_history()
            
            QMessageBox.information(
                self, 
                tr("clear_history_complete", "清空完成"), 
                tr("clear_history_complete_message", "历史记录已清空")
            )
            
    def accept(self):
        """确认对话框"""
        self._apply_settings()
        super().accept()
